package com.allen.library.base;

import android.util.Log;

import com.allen.library.exception.ApiException;
import com.allen.library.interfaces.ISubscriber;
import com.allen.library.manage.RxHttpManager;
import com.sebiotec.basecommon.utils.constant.SjmConstant;
import com.sebiotec.basecommon.utils.tools.ActivityTool;
import com.sebiotec.basecommon.utils.tools.SPUtils;
import com.tencent.bugly.crashreport.CrashReport;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;


/**
 * Created by Allen on 2017/5/3.
 *
 * @author Allen
 * <p>
 * 基类BaseObserver
 */

public abstract class BaseObserver<T> implements Observer<T>, ISubscriber<T> {

    private boolean isShow= SPUtils.get(SjmConstant.ISHOW,true);

    /**
     * 是否隐藏toast
     *
     * @return
     */
    protected boolean isHideToast() {
        return false;
    }

    /**
     * 标记网络请求的tag
     * tag下的一组或一个请求，用来处理一个页面的所以请求或者某个请求
     * 设置一个tag就行就可以取消当前页面所有请求或者某个请求了
     * @return string
     */
    protected String setTag(){
        return null;
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {
        RxHttpManager.get().add(setTag(), d);
        doOnSubscribe(d);
    }

    @Override
    public void onNext(@NonNull T t) {

        doOnNext(t);
    }

    @Override
    public void onError(@NonNull Throwable e) {

//        String responseBody = ((HttpException) e).response().toString();
//        int code = ((HttpException) e).response().code();
//        CustException apiException =new CustException(responseBody,code);
//       if (ApiException.handleException(e).getCode()==501&&SPUtils.get(SjmConstant.ISHOW,true)){
//           Log.d("dialog","1");
//             //token 过期
//            SPUtils.put(SjmConstant.ISHOW,false);
//           LangDialogFragment langDialogFragment = LangDialogFragment.newInstance("1");
//           ActivityTool.getInstance().getLastActivity().getFragmentManager().beginTransaction().add(langDialogFragment, "tag1").commitAllowingStateLoss();
//       }else if (ApiException.handleException(e).getCode()==502&&SPUtils.get(SjmConstant.ISHOW,true)){
//            Log.d("dialog","2");
//            SPUtils.put(SjmConstant.ISHOW,false);
//             //账户已经在别处登录
//           LangDialogFragment langDialogFragment = LangDialogFragment.newInstance("2");
//           ActivityTool.getInstance().getLastActivity().getFragmentManager().beginTransaction().add(langDialogFragment, "tag2").commitAllowingStateLoss();
//
//       }
        CrashReport.postCatchedException(ApiException.handleException(e));
        String error = ApiException.handleException(e).getCode()+"";


//        ToastUtils.showToast(ApiException.handleException(e).getCode()+"");
        setError(error);
    }


    @Override
    public void onComplete() {
        doOnCompleted();
    }


    private void setError(String errorMsg) {
        doOnError(errorMsg);
    }

}
